#include <iostream>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#define PORT 8080

void handle_client(int client_socket) {
    const char *message = "Hello, World!";
    // write(client_socket, message, strlen(message));
    // close(client_socket);
}

int main() {
    // 创建 TCP socket
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        std::cerr << "Socket creation failed!" << std::endl;
        return -1;
    }

    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY; // 本地地址
    server_addr.sin_port = htons(PORT);

    // 绑定端口
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        std::cerr << "Bind failed!" << std::endl;
        return -1;
    }

    // 开始监听
    if (listen(server_socket, 3) < 0) {
        std::cerr << "Listen failed!" << std::endl;
        return -1;
    }

    std::cout << "Server listening on port " << PORT << "..." << std::endl;

    while (true) {
        // 接受客户端连接
        int client_socket = accept(server_socket, nullptr, nullptr);
        if (client_socket < 0) {
            std::cerr << "Accept failed!" << std::endl;
            continue;
        }

        // 处理客户端请求
        handle_client(client_socket);
    }

    close(server_socket);
    return 0;
}
